package com.sls.api.game.servlet;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.google.gson.Gson;
import com.sls.api.game.parser.ReadXingConfig;
import com.sls.api.game.pojo.XingOrderStatusInfo;
import com.sls.api.util.IpUtil;
import com.sls.api.util.ResponseDataXmlFormat;
import com.sls.api.util.UtilMD5Encryption;
import com.sls.core.common.CommonUtil;
import com.sls.core.socket.Head;
import com.sls.core.socket.SocketDTO;

/**
 * 
 * @description 星启天订单最终结果异步通知
 * @author Wangxuegang
 * @date 2012-12-26
 */
public class XingOrderStatusServlet extends SuperServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static Logger log = Logger.getLogger(XingOrderStatusServlet.class);

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setAttribute("org.eclipse.jetty.server.Request.queryEncoding",
				"GBK");
		resp.setContentType("text/html;charset=GBK");
		resp.setStatus(HttpServletResponse.SC_OK);

		// 订单充值状态
		String state = req.getParameter("state");
		// 51订单号
		String exchange_no = req.getParameter("Exchange_no");
		// 商户订单号
		String tranid = req.getParameter("tranid");
		// MD5签名
		String sign = req.getParameter("sign");
		// 订单金额
		String ordermoney = req.getParameter("Ordermoney");
		// 说明
		String remark = req.getParameter("Remark");

		String stateDescrip = "";
		if ("1".equals(state)) {
			stateDescrip = "订单充值成功";
		} else if ("2".equals(state)) {
			stateDescrip = "订单充值失败";
		}
		log.info("星启天回调推送订单处理结果：" + "\n订单最终处理结果：" + stateDescrip + "\n星启天订单号："
				+ exchange_no + "\n手拉手订单号：" + tranid + "\n签名字符串：" + sign
				+ "\n订单金额：" + ordermoney + "\n说明：" + remark);

		boolean flag = checkData(resp, state, exchange_no, tranid, sign,
				ordermoney);
		if (flag) {
			try {
				Gson gson = CommonUtil.gson();
				SocketDTO socketChangeVo = createMsg(state, exchange_no, tranid, 
						sign, ordermoney, remark, req);
				Head head = socketChangeVo.getHead();
				String resCode = head.getResponseCode();
				String resMsg = head.getResponseMessage();
				resMsg = URLEncoder.encode(resMsg, "GBK"); // GBK编码
				String bodyStr = socketChangeVo.getBody();
				String resBodyStr = gson.fromJson(bodyStr, String.class);
				
				String result = ResponseDataXmlFormat.assembleXmlStrAboutXingQiTian(resBodyStr, resCode, resMsg);
				resp.getWriter().write(result);
				resp.getWriter().flush();
				resp.getWriter().close();
			} catch (Exception e) {
				log.error(e);
			}
		}
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	/**
	 * 
	 * @param resp
	 * @param state
	 * @param exchange_no
	 * @param tranid
	 * @param sign
	 * @return
	 * @throws IOException
	 */
	private boolean checkData(HttpServletResponse resp, String state,
			String exchange_no, String tranid, String sign, String ordermoney)
			throws IOException {
		boolean flag = false;
		if ("".equals(state) || state == null) {
			ResponseDataXmlFormat.returnResMsg("101", "缺少必需参数[state]", resp);
		} else if ("".equals(exchange_no) || exchange_no == null) {
			ResponseDataXmlFormat.returnResMsg("101", "缺少必需参数[exchange_no]",
					resp);
		} else if ("".equals(tranid) || tranid == null) {
			ResponseDataXmlFormat.returnResMsg("101", "缺少必需参数[tranid]", resp);
		} else if ("".equals(sign) || sign == null) {
			ResponseDataXmlFormat.returnResMsg("101", "缺少必需参数[sign]", resp);
		} else if ("".equals(ordermoney) || ordermoney == null) {
			ResponseDataXmlFormat.returnResMsg("101", "缺少必需参数[ordermoney]",
					resp);
		} else {
			String signValue = createSignString(state, exchange_no, tranid);
			if (signValue.equals(sign)) {
				flag = true;
			}else {
				StringBuilder strBu = new StringBuilder();
				strBu.append("<result>");
				strBu.append("Fail");
				strBu.append("</result>");
				String xmlStr = strBu.toString();
				resp.getWriter().write(xmlStr);
				resp.getWriter().flush();
				resp.getWriter().close();
			}
		}

		return flag;
	}
	
	
	private String createSignString(String state,
			String exchange_no, String tranid){
		XingOrderStatusInfo info = null;
		String key = null;
		info = ReadXingConfig.readConfig();
		if (info != null) {
			key = info.getUserKey().trim();
		}
		
		StringBuilder strBui = new StringBuilder();
		strBui.append("exchange_no=");
		strBui.append(exchange_no);
		strBui.append("&");
		strBui.append("tranid=");
		strBui.append(tranid);
		strBui.append("&");
		strBui.append("state=");
		strBui.append(state);
		strBui.append("&");
		strBui.append("key=");
		strBui.append(key);
		
		String data = strBui.toString().trim();
		String result = UtilMD5Encryption.createMD5StringOfGB2312(data);
		
		return result;
	}
	
	/**
	 * 向service层发送请求消息
	 * 
	 * @param ret_code
	 * @param sporder_id
	 * @param ordersuccesstime
	 * @param err_msg
	 * @param req
	 * @return
	 */
	private SocketDTO createMsg(String state, String exchange_no,
			String tranid, String sign, String ordermoney, String remark,
			HttpServletRequest req) {
		XingOrderStatusInfo xingOrderStatusInfo = new XingOrderStatusInfo();
		xingOrderStatusInfo.setState(state);
		xingOrderStatusInfo.setExchange_no(exchange_no);
		xingOrderStatusInfo.setTranid(tranid);
		xingOrderStatusInfo.setSign(sign);
		xingOrderStatusInfo.setOrdermoney(ordermoney);
		xingOrderStatusInfo.setRemark(remark);

		SocketDTO socketChangeVo = new SocketDTO();
		Head head = new Head();
		head.setRequestId(UUID.randomUUID().toString());
		head.setServiceCode("020925");// 
		head.setIp(IpUtil.getIpAddr(req));
		head.setUserId("0"); //
		socketChangeVo.setHead(head); // 报文头部
		return super.send(head, xingOrderStatusInfo);
	}

}
